package com.xyzwps.harbor.repo;

import com.xyzwps.harbor.model.UserPassword;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.r2dbc.core.R2dbcEntityTemplate;
import org.springframework.stereotype.Repository;
import reactor.core.publisher.Mono;

import java.util.Optional;

@Repository
public class UserPasswordRepositoryImpl implements UserPasswordRepository {

    @Autowired
    private R2dbcEntityTemplate template;

    @Override
    public Mono<Void> insert(UserPassword userPassword) {
        String sql = "INSERT INTO user_password (user_id, encrypted_password) VALUES (:userId, :password)";
        return template.getDatabaseClient().sql(sql)
                .bind("userId", userPassword.getUserId())
                .bind("password", userPassword.getEncryptedPassword())
                .then();
    }


    @Override
    public Mono<UserPassword> selectByUserId(Long userId) {
        String sql = "SELECT user_id, encrypted_password FROM user_password WHERE user_id = :userId";
        return template.getDatabaseClient().sql(sql)
                .bind("userId", userId)
                .map((row, m) -> {
                    var up = new UserPassword();
                    up.setUserId(Optional.ofNullable(row.get("user_id", Long.class)).orElseThrow());
                    up.setEncryptedPassword(Optional.ofNullable(row.get("encrypted_password", String.class)).orElseThrow());
                    return up;
                }).first();
    }
}